#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>

using namespace std;

const int NUM = 5;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;


void* threadRoutine(void* args)
{
    string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&mutex);
        //未来呢，临界区的代码执行，一定会有条件限制的，但又不能让它重复的申请锁，释放锁，因此可以整个条件变量，让它变得同步
        //if(...)
        pthread_cond_wait(&cond,&mutex); //让线程都在这个条件变量的队列中等待，由主线程去唤醒它们
        cout << name << " is running" << endl;
        
        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}


int main()
{
    pthread_t tids[NUM];
    for(int i = 0; i < NUM; i++)
    {
        char* name = new char[64];
        snprintf(name,64,"thread-%d",i+1);
        pthread_create(tids + i,nullptr, threadRoutine,(void*)name);
    }

    sleep(3);  //让所有线程都在条件变量下进行等待

    //唤醒线程
    while(true)
    {
        cout << "main thread is wakeup child thread" << endl;
        // pthread_cond_signal(&cond);  //唤醒一个线程
        pthread_cond_broadcast(&cond);  //全部唤醒
        sleep(1);
    }

    for(int i = 0; i < NUM; i++)
    {
        pthread_join(tids[i],nullptr);
    }


    return 0;
}